package com.atguigu.flink.day01;

import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @author Felix
 * @date 2023/11/29
 * 该案例演示了以流的形式处理（DataStreamAPI）的方式读取文件数据，计算wordcount
 */
public class Flink02_stream_bound {
    public static void main(String[] args) throws Exception {
        //TODO 1.指定流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setRuntimeMode(RuntimeExecutionMode.BATCH);

        //TODO 2.从指定的文件中读取数据
        DataStreamSource<String> textDS = env.readTextFile("D:\\dev\\workspace\\bigdata0710-parent\\flink0710\\input\\word.txt");
        //TODO 3.对读取的数据进行转换     封装为二元组
        SingleOutputStreamOperator<Tuple2<String, Long>> tupleDS = textDS.flatMap(new FlatMapFunction<String, Tuple2<String, Long>>() {
            @Override
            public void flatMap(String lineStr, Collector<Tuple2<String, Long>> out) throws Exception {
                String[] wordArr = lineStr.split(" ");
                for (String word : wordArr) {
                    out.collect(Tuple2.of(word, 1L));
                }
            }
        });

        //TODO 4.分组
        KeyedStream<Tuple2<String, Long>, Tuple> keyedDS = tupleDS.keyBy(0);

        //TODO 5.聚合
        SingleOutputStreamOperator<Tuple2<String, Long>> sumDS = keyedDS.sum(1);
        sumDS.print();

        env.execute();

    }
}
